﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RayDen.Library.Core;
using RayDen.Library.Core.Primitives;

namespace SmallVCM
{
    public static class Consts
    {

        public const float EPS_COSINE = 1e-6f;
        public const float EPS_RAY = 1e-3f;
    }


    public class Utils
    {
        public static Vector SampleCosHemisphereW(UV aSamples, out float oPdfW)
        {
            float term1 = 2f * MathLab.M_PI * aSamples.U;
            float term2 = MathLab.Sqrt(1f - aSamples.V);

            Vector ret = new Vector(
                MathLab.Cos(term1) * term2,
                MathLab.Sin(term1) * term2,
                MathLab.Sqrt(aSamples.V));

            oPdfW = ret.z * MathLab.INVPI;

            return ret;
        }

        public static float CosHemispherePdfW(
            Normal aNormal,
            Vector aDirection)
        {
            return Math.Max(0f, Vector.Dot(ref aNormal, ref aDirection)) * MathLab.INVPI;
        }

        public static float FresnelDielectric(float aCosInc, float mIOR)
        {
            if (mIOR < 0)
                return 1f;

            float etaIncOverEtaTrans;

            if (aCosInc < 0f)
            {
                aCosInc = -aCosInc;
                etaIncOverEtaTrans = mIOR;
            }
            else
            {
                etaIncOverEtaTrans = 1f / mIOR;
            }

            float sinTrans2 = Sqr(etaIncOverEtaTrans) * (1f - Sqr(aCosInc));
            float cosTrans = MathLab.Sqrt(Math.Max(0f, 1f - sinTrans2));

            float term1 = etaIncOverEtaTrans * cosTrans;
            float rParallel =
                (aCosInc - term1) / (aCosInc + term1);

            float term2 = etaIncOverEtaTrans * aCosInc;
            float rPerpendicular = (term2 - cosTrans) / (term2 + cosTrans);

            return 0.5f * (Sqr(rParallel) + Sqr(rPerpendicular));
        }

        public static float Sqr(float aCosInc)
        {
            return aCosInc * aCosInc;
        }
    }
}
